package com.itheima.service.impl;

import com.itheima.aop.Log;
import com.itheima.mapper.DeptMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.Dept;
import com.itheima.pojo.DeptLog;
import com.itheima.service.DeptLogService;
import com.itheima.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.FileInputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class DeptServiceImpl implements DeptService {

    //依赖注入
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private DeptLogService deptLogService;

    /**
     * 查询部门管理列表
     *
     * @return
     */
    @Override
    public List<Dept> list() {
        //调用mapper层方法
        List<Dept> list = deptMapper.list();
        //返回数据
        return list;
    }

    /**
     * 根据id删除部门
     *
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    //事务只能抓取运行期异常，而属性rollbackFor可以指定抓取的异常范围，在出现错误时回滚
    public void deleteById(Integer id) throws IOException {

        try {
            //调用mapper层,无返回值
            deptMapper.deleteById(id);
//            int i = 1/0;
            new FileInputStream("");
            empMapper.deleteByDeptId(id);
        } finally {
            //记录删除的部门日志信息
            DeptLog deptLog = new DeptLog();
            //补全字段信息
            deptLog.setCreateTime(LocalDateTime.now());
            deptLog.setDescription("删除了" + id + "部门");

            deptLogService.insert(deptLog);
        }

    }

    /**
     * 添加部门
     *
     * @param dept
     */
    @Override
    public void insert(Dept dept) {
        //完善数据
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        //调用mapper层方法
        deptMapper.insert(dept);
    }

    /**
     * id查询部门信息
     *
     * @param id
     * @return Dept
     */
    @Override
    public Dept selectById(Integer id) {
        //调用mapper层
        Dept dept = deptMapper.selectById(id);
        return dept;
    }

    /**
     * 修改部门信息
     *
     * @param dept
     */
    @Override
    public void put(Dept dept) {
        //完善字段信息
        dept.setUpdateTime(LocalDateTime.now());
        //调用mapper层,无返回值
        deptMapper.put(dept);

    }
}
